<template>
  <div class="daily-question-section mb-6 mt-6">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
      <!-- 左侧：时钟和日历 -->
      <div class="lg:col-span-1">
        <div class="bg-white rounded-lg shadow-md border border-gray-200 p-4">
          <!-- 左右布局：时钟和统计信息 -->
          <div class="flex items-center space-x-5 mb-4">
            <!-- 左侧：时钟 -->
            <div class="flex-shrink-0">
              <!-- 时钟背景 -->
              <div class="relative w-18 h-18 bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500 rounded-full shadow-md">
                <!-- 时钟指针背景 -->
                <div class="absolute inset-1.5 bg-white rounded-full shadow-inner flex items-center justify-center">
                  <!-- 时钟中心点 -->
                  <div class="w-1 h-1 bg-gray-400 rounded-full"></div>
                  <!-- 时针 -->
                  <div class="absolute w-0.5 h-4 bg-gray-700 rounded-full origin-bottom bottom-1/2" 
                       :style="{ transform: `rotate(${hourAngle}deg)` }"></div>
                  <!-- 分针 -->
                  <div class="absolute w-0.5 h-5 bg-gray-800 rounded-full origin-bottom bottom-1/2" 
                       :style="{ transform: `rotate(${minuteAngle}deg)` }"></div>
                  <!-- 秒针 -->
                  <div class="absolute w-0.5 h-5 bg-red-500 rounded-full origin-bottom bottom-1/2" 
                       :style="{ transform: `rotate(${secondAngle}deg)` }"></div>
                </div>
              </div>
            </div>
            
            <!-- 右侧：时间和统计信息 -->
            <div class="flex-1 min-w-0">
              <!-- 时间显示 -->
              <div class="mb-3">
                <div class="text-lg font-mono font-semibold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
                  {{ currentTime }}
                </div>
                <div class="text-sm text-gray-600 font-medium">
                  {{ currentDate }}
                </div>
              </div>
              
              <!-- 统计信息 -->
              <div class="grid grid-cols-1 gap-1">
                <!-- 加载状态 -->
                <div v-if="statsLoading" class="flex items-center justify-center p-4">
                  <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
                  <span class="ml-2 text-sm text-gray-600">加载中...</span>
                </div>
                
                <!-- 错误状态 -->
                <div v-else-if="statsError" class="p-2 bg-red-50 rounded-md border border-red-200">
                  <div class="flex items-center">
                    <svg class="w-4 h-4 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                    </svg>
                    <span class="text-xs text-red-600">{{ statsError }}</span>
                  </div>
                </div>
                
                <!-- 正常状态 -->
                <template v-else>
                  <div class="flex items-center justify-between p-2 bg-green-50 rounded-md border border-green-200">
                    <div class="flex items-center">
                      <div class="w-3 h-3 bg-green-500 rounded-full flex items-center justify-center mr-2">
                        <svg class="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                          <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 8zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                        </svg>
                      </div>
                      <span class="text-xs text-gray-700 font-medium">已解决</span>
                    </div>
                    <span class="text-sm font-semibold text-green-600">{{ todayStats.solved }}</span>
                  </div>
                  
                  <div class="flex items-center justify-between p-2 bg-blue-50 rounded-md border border-blue-200">
                    <div class="flex items-center">
                      <div class="w-3 h-3 bg-blue-500 rounded-full flex items-center justify-center mr-2">
                        <svg class="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                          <path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd"/>
                        </svg>
                      </div>
                      <span class="text-xs text-gray-700 font-medium">连续天数</span>
                    </div>
                    <span class="text-sm font-semibold text-blue-600">{{ todayStats.streak }}</span>
                  </div>
                  
                  <div class="flex items-center justify-between p-2 bg-purple-50 rounded-md border border-purple-200">
                    <div class="flex items-center">
                      <div class="w-3 h-3 bg-purple-500 rounded-full flex items-center justify-center mr-2">
                        <svg class="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                          <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                      </div>
                      <span class="text-xs text-gray-700 font-medium">总题数</span>
                    </div>
                    <span class="text-sm font-semibold text-purple-600">{{ todayStats.total }}</span>
                  </div>
                </template>
              </div>
            </div>
          </div>
          
          <!-- 快速操作按钮 -->
          <div class="border-t border-gray-200 pt-3">
            <div class="flex space-x-2">
              <button 
                @click="goToRandomQuestion"
                class="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-md hover:from-purple-600 hover:to-pink-600 transition-all duration-200 shadow-sm hover:shadow-md"
              >
                <svg class="w-3 h-3 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                随机一题
              </button>
              <button 
                @click="goToHistory"
                class="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium bg-gradient-to-r from-gray-500 to-gray-600 text-white rounded-md hover:from-gray-600 hover:to-gray-700 transition-all duration-200 shadow-sm hover:shadow-md"
              >
                <svg class="w-3 h-3 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 8zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd"/>
                </svg>
                历史记录
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧：每日一题 -->
      <div class="lg:col-span-2">
        <DailyQuestionCard />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import DailyQuestionCard from './DailyQuestionCard.vue'
import { getRandomQuestionFromCurrentFilters } from '@/api/randomQuestion'
import { userApi } from '@/api/user'
import { getDailyQuestionStats } from '@/api/dailyQuestion'

const router = useRouter()

// 响应式数据
const currentTime = ref('')
const currentDate = ref('')
const todayStats = ref({
  solved: 0,
  streak: 0,
  total: 0
})

// 加载状态
const statsLoading = ref(false)
const statsError = ref('')

// 时钟指针角度
const hourAngle = ref(0)
const minuteAngle = ref(0)
const secondAngle = ref(0)

let timeInterval: number | null = null

// 更新时间
const updateTime = () => {
  const now = new Date()
  
  // 数字时间显示
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
  currentDate.value = now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
  
  // 计算时钟指针角度
  const hours = now.getHours()
  const minutes = now.getMinutes()
  const seconds = now.getSeconds()
  
  // 时针角度：每小时30度，加上分钟的影响
  hourAngle.value = (hours % 12) * 30 + minutes * 0.5
  
  // 分针角度：每分钟6度
  minuteAngle.value = minutes * 6
  
  // 秒针角度：每秒6度
  secondAngle.value = seconds * 6
}

// 获取今日统计
const fetchTodayStats = async () => {
  statsLoading.value = true
  statsError.value = ''
  
  try {
    // 并行获取用户统计和每日一题统计
    const [userStatsResponse, dailyStatsResponse] = await Promise.all([
      userApi.getCurrentUserStats(),
      getDailyQuestionStats()
    ])
    
    const userStats = userStatsResponse.data
    const dailyStats = dailyStatsResponse
    
    // 更新统计数据
    todayStats.value = {
      solved: userStats?.solved_count || 0,
      streak: userStats?.consecutive_days || 0,
      total: userStats?.solved_count || 0
    }
  } catch (error: any) {
    console.error('获取今日统计失败:', error)
    statsError.value = error?.message || '获取统计信息失败'
    
    // 设置默认值
    todayStats.value = {
      solved: 0,
      streak: 0,
      total: 0
    }
  } finally {
    statsLoading.value = false
  }
}

// 跳转到随机题目
const goToRandomQuestion = async () => {
  try {
    // 获取当前页面的筛选条件（如果有的话）
    const currentFilters = getCurrentPageFilters()
    
    // 调用API获取随机题目
    const randomQuestion = await getRandomQuestionFromCurrentFilters(currentFilters)
    
    if (randomQuestion) {
      // 跳转到随机题目详情页
      router.push(`/question/${randomQuestion.id}`)
    } else {
      // 如果没有符合条件的题目，显示提示并跳转到题库
      alert('没有符合条件的题目，将跳转到题库页面')
      router.push('/questions')
    }
  } catch (error) {
    console.error('获取随机题目失败:', error)
    // 出错时跳转到题库页面
    router.push('/questions')
  }
}

// 获取当前页面的筛选条件
const getCurrentPageFilters = () => {
  // 这里可以根据当前页面状态获取筛选条件
  // 例如从URL参数、Vuex store或localStorage中获取
  const urlParams = new URLSearchParams(window.location.search)
  const filters: any = {}
  
  // 从URL参数中获取筛选条件
  if (urlParams.get('difficulty')) {
    filters.difficulty = urlParams.get('difficulty')
  }
  if (urlParams.get('tags')) {
    filters.tags = urlParams.get('tags')?.split(',')
  }
  if (urlParams.get('category')) {
    filters.category = urlParams.get('category')
  }
  if (urlParams.get('solved')) {
    filters.solved = urlParams.get('solved') === 'true'
  }
  
  return filters
}

// 跳转到历史记录
const goToHistory = () => {
  router.push('/daily-question/history')
}

// 组件挂载
onMounted(() => {
  updateTime()
  fetchTodayStats()
  
  // 每秒更新时间
  timeInterval = setInterval(updateTime, 1000)
})

// 组件卸载
onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.daily-question-section {
  max-width: 100%;
}

@media (min-width: 1024px) {
  .daily-question-section {
    max-width: 1200px;
  }
}
</style>
